package com.cari.oa.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.cari.oa.domain.AttachmentEntity;
import com.cari.oa.domain.CommentEntity;
import com.cari.oa.domain.MarketProjectEntity;
import com.cari.oa.domain.NotificationEntity;
import com.cari.oa.domain.ReqEntity;
import com.cari.oa.domain.ReqTypeEntity;
import com.cari.oa.domain.ReqUserRefEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.service.AttachmentService;
import com.cari.oa.service.CommentService;
import com.cari.oa.service.MarketProjectService;
import com.cari.oa.service.NotificationService;
import com.cari.oa.service.ReqService;
import com.cari.oa.service.ReqTypeService;
import com.cari.oa.service.ReqUserRefService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
* Title: ReqController
* Description:需求control
* Company:   cari 
* @author    hjx 
* @date      2013-3-12
*/
@Controller
@SessionAttributes({"username","usercnname"})
public class ReqController extends BaseDownloadController {

	@Resource
	private ReqService reqService;
	@Resource
	private SysDictItemService sysDictItemService;
	@Resource
	private SysUserService sysUserService;
	@Resource
	private ReqTypeService reqTypeService;
	@Resource
	private CommentService commentService;
	@Resource
	private AttachmentService attachmentService;
	@Resource
	private ReqUserRefService reqUserRefService;
	@Resource
    private MarketProjectService marketProjectService;
	@Resource
	private NotificationService notificationService;
	
	public static final String MODULE_NAME = "REQ_MANAGE";
	
	private static final Logger logger = LoggerFactory.getLogger(ReqController.class);
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
    
	/**
	* Title: list
	* Description:分页查询需求数据
	* @author    hjx 
	* @date       2013-3-13 
	* @param title     标题
	* @param initiator 发起人
	* @param status    状态
	* @param reqType   需求类型
	* @param curPage
	* @param modelMap
	* @return
	*/
    @RequestMapping("myreq/list.do")
    public String list(@ModelAttribute("username") String username,
    		String title, String sortType, 
    		String status, String reqType,
    		String project,String pName, 
    		Integer curPage, ModelMap modelMap) {
       try{
	    	if(curPage == null) curPage = 1;
	     
	    	//List<MarketProjectEntity> projects = marketProjectService.getProjectByApplyUser(username);
	    	//if(StrUtils.isEmpty(project) && projects !=null && projects.size()>0){
	    	//	project = projects.get(0).getId();
	    	//	pName = projects.get(0).getName();
	    	//}
	    	
	    	long totalRecords = reqService.getCount(title,username,null, status, reqType, sortType,project);
		    long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
		    
	        List<ReqEntity> reqList = reqService.getPage(title,username, null, status, reqType, sortType,project, curPage, Contants.PAGE_SIZE);
	        List<SysDictItemEntity> statusList = sysDictItemService.getItemsByGroupName("reqStatus");
	        List<Map<String,String>> typeList = reqTypeService.getReqTypeNameAndPerson();
	    	List<SysDictItemEntity> itemList =   sysDictItemService.getItemsByGroupName("reqStatus"); 
	    	List<ReqTypeEntity> allReqType = reqTypeService.getAll();
	    	List<SysDictItemEntity> sList =   sysDictItemService.getItemsByGroupName("reqResponsible"); 

	    	for(ReqEntity cur : reqList)
	        {
	        	for(Map<String,String> map : typeList)
	        	{
	        		if(StrUtils.isNotEmpty(cur.getReqType()) && cur.getReqType().equals(map.get("typeId")))
	        		{   
	        			if(StrUtils.isEmpty(cur.getPrincipal())){
		        			cur.setTypeName(map.get("typeName"));
		        			cur.setPrincipal(map.get("cnName"));
	        			} else {
	        				cur.setPrincipal(cur.getPrincipal()+","+map.get("cnName"));
	        			}
	        		}
	        	}
	        }
	        
	        modelMap.addAttribute("allReqType", allReqType);
	       // modelMap.addAttribute("projects", projects);
	        modelMap.addAttribute("itemList", itemList);
	        modelMap.addAttribute("sList", sList);
	        modelMap.addAttribute("typeList", typeList);
	        modelMap.addAttribute("statusList", statusList);
	        modelMap.addAttribute("reqList", reqList);
	        modelMap.addAttribute("curPage", curPage);
	        modelMap.addAttribute("totalPage", totalPage);
	        modelMap.addAttribute("totalRecords", totalRecords);
	        modelMap.addAttribute("title", title);
	        modelMap.addAttribute("status", status);
	        modelMap.addAttribute("reqType", reqType);
	        modelMap.addAttribute("sortType", sortType);
	        modelMap.addAttribute("project", project);
	        modelMap.addAttribute("pName", pName);
       }catch(Exception e) {
    	   logger.error("获取我的需求列表出错", e);
       }
        return "req/myreq/list";
    }
    
    /**
    * Title: enterInsert
    * Description:进入添加页面
    * @author     hjx 
    * @date       2013-3-13 
    * @param qs
    * @param projectId
    * @param modelMap
    * @return
    */
    @RequestMapping(value = "myreq/insert.do", method = RequestMethod.GET)
    public String enterInsert(@ModelAttribute("username") String username,String qs,String projectId, ModelMap modelMap) {
    	List<MarketProjectEntity> projects = marketProjectService.getProjectByApplyUser(username);
    	List<SysDictItemEntity> items = sysDictItemService.getItemsByGroupName("reqResponsible");
    	modelMap.put("projects", projects);
    	modelMap.put("items", items);
    	return "req/myreq/insert";
    }
    
    /**
    * Title: postInsert
    * Description:添加需求
    * @author    hjx 
    * @date       2013-3-13 
    * @param username
    * @param reqEntity
    * @param result
    * @return
    */
    @RequestMapping(value = "myreq/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username,@ModelAttribute("usercnname") String usercnname, @Valid ReqEntity reqEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        reqEntity.setInitiator(username);
        reqEntity.setStatus("submitted");       //新建时默认状态为：已提交
        reqEntity.setCnName(usercnname);
        reqService.insert(reqEntity);
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增需求" + reqEntity.getTitle());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        resultMap.put("reqId", reqEntity.getId());
        return JSON.toJSONString(resultMap);
    }
    
	/**
	* Title: enterEdit
	* Description:进入修改页面
	* @author    hjx 
	* @date       2013-3-13 
	* @param id
	* @param qs
	* @param modelMap
	* @return
	*/
    @RequestMapping(value = "myreq/edit.do", method = RequestMethod.GET)
    public String enterEdit(String id, String qs, String pName, ModelMap modelMap) {
    	ReqEntity req = reqService.getById(id);
    	List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
    	List<CommentEntity> comList = commentService.getListByObjID(id,CommentService.CMT_REQ);
    	List<SysDictItemEntity> statusList = sysDictItemService.getItemsByGroupName("reqStatus");
    	List<SysDictItemEntity> sList =   sysDictItemService.getItemsByGroupName("reqResponsible"); 
    	if(StrUtils.isEmpty(pName) && req.getProject() != null)
    	    pName = marketProjectService.getById(req.getProject()).getName();
        modelMap.addAttribute("sList", sList);
        modelMap.addAttribute("statusList", statusList);
        modelMap.addAttribute("comList", comList);
    	modelMap.addAttribute("attList", attList);
        modelMap.addAttribute("req", req);
        modelMap.addAttribute("pName", pName);
        modelMap.addAttribute("qs", qs);
        return "req/myreq/edit";
    }
    
    /**
    * Title: postEdit
    * Description:修改需求
    * @author     hjx 
    * @date       2013-3-13 
    * @param username
    * @param req
    * @param result
    * @return
    */
    @RequestMapping(value = "myreq/edit.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username,String sta,String id, @Valid ReqEntity req, BindingResult result) {
        if(StrUtils.isNotEmpty(sta))      //归档操作
        {
        	req = reqService.getById(id);
        	req.setStatus(sta);
        }else                             //修改基本信息
        {
        	 if(result.hasFieldErrors())
                 return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        }
        reqService.update(req);
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改需求" + req.getTitle());
        return Utils.normalJsonResp();
    }
    
    
    /**
    * Title: upload
    * Description:上传
    * @author    hjx 
    * @date       2013-3-13 
    * @param username
    * @param request
    * @param response
    * @param result
     */
	@RequestMapping("myreq/upload.do")
	public void upload(@ModelAttribute("usercnname") String username,HttpServletRequest request,HttpServletResponse response,BindingResult result) {
		MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
		multipartRequest.setAttribute("ObjectType",AttachmentService.BUG_ATTACHEMENT_TYPE);
		multipartRequest.setAttribute("ObjectId",multipartRequest.getParameter("reqId"));
		super.upload(username, multipartRequest);
	}
	
	/**
	 * 下载
	 */
	@RequestMapping("myreq/download.do")
	public void download(String fileName,String path,HttpServletRequest request, HttpServletResponse response) {
		super.download(fileName, path, request, response);
	}
	
	/**
	 * 删除文件
	 */
	@RequestMapping("myreq/deleteFile.do")
	@ResponseBody
    public String postDelete(@ModelAttribute("username") String username,HttpServletRequest request, String id,String path) {
		return super.postDelete(username, request, id, path);
    }
	
	/**
	* Title: delete
	* Description:删除需求
	* @author     hjx 
	* @date       2013-3-15 
	* @param username
	* @param id
	* @return
	*/
	@RequestMapping("myreq/delete.do")
	@ResponseBody
    public String delete(@ModelAttribute("username") String username,HttpServletRequest request, String id) {
		ReqEntity req = reqService.getById(id);
		List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
        if(req == null) 
        	return Utils.errorJsonResp("该需求不存在！");
        reqService.deleteById(id);
        for(AttachmentEntity att : attList)
        {
        	this.postDelete(username, request, att.getId(),att.getPath());
        }
        SysOperLogController.addOperLog(username, MODULE_NAME, "删除需求成功" + req.getTitle());
        return Utils.normalJsonResp();
    }
	
	/**
	* Title: delete
	* Description:撤销需求
	* @author     hjx 
	* @date       2013-3-15 
	* @param username
	* @param id
	* @return
	*/
	@RequestMapping("myreq/revoke.do")
	@ResponseBody
    public String revoke(@ModelAttribute("username") String username, String id,String revoke) {
		ReqEntity req = reqService.getById(id);
		req.setStatus("undone");
		req.setRevokeReason(revoke);
        reqService.update(req);
        SysOperLogController.addOperLog(username, MODULE_NAME, "撤销需求成功" + req.getTitle());
        return Utils.normalJsonResp();
    }
	

    /**
    * Title: enterView
    * Description:查看页面
    * @author     hjx 
    * @date       2013-3-13 
    * @param id
    * @param modelMap
    * @return
    */
    @RequestMapping(value = "myreq/view.do", method = RequestMethod.GET)
    public String enterView(String id,String qs, ModelMap modelMap) {
    	ReqEntity req = reqService.getById(id);
    	List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
    	List<CommentEntity> comList = commentService.getListByObjID(id,CommentService.CMT_REQ);
    	List<SysDictItemEntity> itemList =   sysDictItemService.getItemsByGroupName("reqStatus"); 
        List<ReqTypeEntity> typeList = reqTypeService.getAll();
        modelMap.addAttribute("typeList", typeList);
        ReqUserRefEntity ruf = reqUserRefService.getByReqType(req.getReqType());
        if(ruf.getEnname()!=null)
        modelMap.addAttribute("principal", sysUserService.getByEnname(ruf.getEnname()).getCnname());
    	List<SysDictItemEntity> sList =   sysDictItemService.getItemsByGroupName("reqResponsible"); 
        modelMap.addAttribute("sList", sList);
        modelMap.addAttribute("itemList", itemList);
        modelMap.addAttribute("comList", comList);
        modelMap.addAttribute("attList", attList);
        modelMap.addAttribute("req", req);
        modelMap.addAttribute("qs", qs);
        return "req/myreq/view";
    }
    
    /**
    * Title: comment
    * Description: 发表留言
    * @author      hjx 
    * @date        2013-3-13 
    * @param username
    * @param usercnname
    * @param objectId
    * @param content
    * @param modelMap
    * @return
     * @throws IOException 
    */
    @RequestMapping(value = "myreq/comment.do" , method = RequestMethod.POST)
    public void comment(@ModelAttribute("username") String username,@ModelAttribute("usercnname") String usercnname,HttpServletResponse response,String objectId, String comment, ModelMap modelMap) throws IOException {
    	CommentEntity com = new CommentEntity();
    	com.setId(UUID.randomUUID().toString());
    	com.setContent(comment);
    	com.setObjectId(objectId);
    	com.setObjectType(CommentService.CMT_REQ);
    	com.setUserEnname(username);
    	com.setUserCnname(usercnname);
    	ReqEntity req = reqService.getById(objectId);
    	req.setNewRepTime(com.getCreateTime());
    	    	
    	commentService.insert(com);
    	reqService.update(req);
    	sendMeg(username,usercnname,req);
    	
    	Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        resultMap.put("createTime",df.format(com.getCreateTime()));
    	SysOperLogController.addOperLog(username, MODULE_NAME, "新增评论" + com.getContent());
    	PrintWriter p =response.getWriter();
    	p.write(JSON.toJSONString(resultMap));
    	p.close();
    }
    
    /**
     * 发起回复信息
    *@param username
    *@param req
    *@author hjx
    *@date 2013-5-10上午11:35:42
     */
    private void sendMeg(String username, String cnname, ReqEntity req)
    {
    	List<ReqUserRefEntity> rus = reqService.getAllReqPrincipal(req.getId()); 
    	if(!username.equals(req.getInitiator()))  //不是发起人
    	{
    		boolean yw = true;
    		for(ReqUserRefEntity r : rus)         
    		{
    			if(r.getEnname().equals(username))
    			{
    				yw = false;
    				String title = "负责人："+username+" 有了最新回复";
        			NotificationEntity n = new NotificationEntity(title, title, username, cnname, req.getInitiator(),req.getCnName(), 1);
        			notificationService.insert(n);    //通知发起人
    			}
    		}
    		if(yw)                                //运维
    		{
    			String title ="运维人员："+username+" 有了最新回复";
    			NotificationEntity n = new NotificationEntity(title, title, username, cnname, req.getInitiator(),req.getCnName(), 1);
    			notificationService.insert(n);    //通知发起人
    			for(ReqUserRefEntity r : rus)     //通知负责人
        		{
        			NotificationEntity noti = new NotificationEntity(title, title, username, cnname, r.getEnname(), r.getCnname(), 1);
        			notificationService.insert(noti);
        		}
    		}
    	}else                                     //发起人
    	{
    		for(ReqUserRefEntity r : rus)         //通知负责人
    		{
    			NotificationEntity noti = new NotificationEntity("发起人："+username+" 有了最新回复",
    			"发起人："+username+" 有了最新回复",  username, cnname, r.getEnname(), r.getCnname(), 1);
    			notificationService.insert(noti);
    		}
    	}
    }
}
